from django import forms
from django.core.exceptions import ValidationError


from app01.utils.form.bootsrapform import BootStrapForm, BootStrapModelForm
from app01 import models
from app01.utils.form.widgets import ColorRadioSelect




class ProjectModelForm(BootStrapModelForm):
    # desc = forms.CharField(widgets=forms.Textarea)
    bootStrap_class_exclude = ["color"]
    
    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'desc': forms.Textarea,
            'color': ColorRadioSelect(attrs={"class":"color-radio"})
            
        }
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        """ 项目效验 """
        name = self.cleaned_data["name"]
        creator = self.request.tracer.user
        # 1.判断当前用户是否已经创建项目
        exist = models.Project.objects.filter(name=name,creator=creator).exists()
        if exist:
           raise ValidationError("项目已创建")

        # 2.当前用户额度是否支持创建项目
        # 最多创建多少项目
        project_num = self.request.tracer.price_policy.project_num

        # 已经创建多少项目
        project_count = models.Project.objects.filter(creator=creator).count()

        if project_count >= project_num:
          raise  ValidationError("项目个数已满, 如需更多请开通VIP")

        return name

        

